<template>
    <view class="container">

        <!-- <view class="header">
            <image class="avatar" :src="userAvatar || '/static/default-avatar.png'" @click="handleUserClick" />
        </view> -->

        <scroll-view class="chat-container" scroll-y="true" :scroll-top="scrollTop">
            <view class="loading" v-if="isHistoryLoading">
                <text>加载历史记录中...</text>

            </view>

            <!-- 空状态提示 -->
            <view class="empty-state" v-if="chatHistory.length === 0">
                <image class="empty-image" src="/static/assistant-avatar.png"></image>
                <text class="empty-text">您好！我是莒县旅游智能助手，请问有什么可以帮您？</text>
                <view class="suggestion-container">
                    <view class="suggestion-item" @click="useQuestion('莒县有哪些著名景点？')">
                        <text>莒县有哪些著名景点？</text>
                    </view>
                    <view class="suggestion-item" @click="useQuestion('介绍一下莒县的历史文化')">
                        <text>介绍一下莒县的历史文化</text>
                    </view>
                    <view class="suggestion-item" @click="useQuestion('莒县特色美食有哪些？')">
                        <text>莒县特色美食有哪些？</text>
                    </view>
                </view>
            </view>

            <!-- 添加清除历史记录按钮 -->
            <view class="clear-history-button" v-if="chatHistory.length > 0" @click="clearChatHistory">
                <text class="clear-history-text">清除对话记录</text>
            </view>

            <view v-for="(item, index) in chatHistory" :key="index" class="message-item" :class="item.type">
                <view class="message-avatar">
                    <image
                        :src="item.type === 'user' ? (userAvatar || '/static/default-avatar.png') : '/static/assistant-avatar.png'" />
                </view>
                <view class="message-content">
                    <!-- 用户消息直接显示文本 -->
                    <text v-if="item.type === 'user'">{{ item.content }}</text>
                    <!-- 助手消息使用Markdown渲染 -->
                    <rich-text v-else :nodes="renderMarkdown(item.content)" class="markdown-content"></rich-text>





                </view>
            </view>
        </scroll-view>

        <view class="input-area">
            <voice-text-input 
                v-model="input" 
                :loading="isLoading" 
                @send="submit">
            </voice-text-input>
        </view>

        <!-- 添加底部安全区域，避免内容被TabBar遮挡 -->
        <view class="safe-bottom"></view>

        <!-- 修改登录按钮区域 -->
        <view class="login-modal" v-if="showLoginModal">
            <view class="login-container">
                <view class="login-title">登录提示</view>
                <view class="login-content">请登录以使用完整功能</view>
                <view class="login-buttons">
                    <button class="cancel-btn" @click="cancelLogin">取消</button>
                    <button class="login-btn" @click="handleLogin">微信登录</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue';
import { marked } from 'marked'; // Changed from 'import marked from 'marked''
import { Prism } from 'prismjs';
import { useAuthStore } from '@/stores/auth'; // 导入 auth store
import VoiceTextInput from '@/components/voice-text-input/voice-text-input.vue';

export default defineComponent({
    components: {
        VoiceTextInput
    },
    setup() {
        const userAvatar = ref('');
        const userName = ref('');
        const userInfo = ref(null);
        const input = ref('');
        const chatHistory = ref([]);
        const isLoading = ref(false);
        const isRecording = ref(false);
        const isHistoryLoading = ref(false);
        const scrollTop = ref(0);
        let recorderManager = null;
        const localHistoryKey = 'chat_history';
        const maxLocalHistoryItems = 100;
        const showLoginModal = ref(false);
        const hasPromptedLogin = ref(false);
        
        // 使用 Pinia 认证存储
        const authStore = useAuthStore();

        onMounted(() => {
            checkLoginStatus();
            initRecorderManager();
            loadLocalChatHistory();
            initMarked(); // 初始化Markdown解析器

            // 处理从其他页面传入的question参数
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            const options = currentPage.options || {};

            if (options.question) {
                const decodedQuestion = decodeURIComponent(options.question);
                // 设置到输入框
                input.value = decodedQuestion;

                // 自动发送问题
                nextTick(() => {
                    submit();
                });
            }

            // 处理语音输入标志
            if (options.voiceInput && options.voiceInput === 'true') {
                nextTick(() => {
                    startVoiceRecord();
                });
            }
        });

        // 检查登录状态
        function checkLoginStatus() {
            // 使用 authStore 检查登录状态
            if (authStore.isLoggedIn && authStore.userInfo) {
                userInfo.value = authStore.userInfo;
                userAvatar.value = userInfo.value.avatarUrl;
                userName.value = userInfo.value.nickName;
            }
        }

        // 处理用户头像点击
        function handleUserClick() {
            if (!authStore.isLoggedIn) {
                login();
            } else {
                uni.showActionSheet({
                    itemList: ['个人信息', '清空聊天记录', '退出登录'],
                    success: (res) => {
                        if (res.tapIndex === 0) {
                            uni.navigateTo({
                                url: '/pages/user/profile'
                            });
                        } else if (res.tapIndex === 1) {
                            clearChatHistory();
                        } else if (res.tapIndex === 2) {
                            logout();
                        }
                    }
                });


            }
        }

        // 微信登录逻辑 - 简化版
        function login() {
            showLoginModal.value = true;
            hasPromptedLogin.value = true;
        }

        // 取消登录
        function cancelLogin() {
            showLoginModal.value = false;
            uni.showToast({
                title: '您已取消登录',
                icon: 'none'
            });
        }

        // 处理登录 - 整合 authStore
        function handleLogin() {
            showLoginModal.value = false;
            uni.showLoading({
                title: '登录中...'
            });

            uni.login({
                provider: 'weixin',
                success: (loginRes) => {
                    if (loginRes.code) {
                        const accountInfo = uni.getAccountInfoSync();
                        console.log(accountInfo.miniProgram.appId); // 小程序 appId
                        // 只发送code到后端换取token
                        uni.request({
                            url: 'https://tushuoit.com/api/ju/auth/login/wechat',
                            method: 'POST',
                            data: {
                                code: loginRes.code,
                                appId: accountInfo.miniProgram.appId
                            },
                            success: (res) => {
                                if (res.data && res.data.access_token) {
                                    // 使用 Pinia store 更新认证状态
                                    authStore.setAuthData({
                                        access_token: res.data.access_token,
                                        token_type: res.data.token_type || 'bearer',
                                        open_id: res.data.open_id || '',
                                        union_id: res.data.union_id || ''
                                    });

                                    // 后端应该返回用户信息
                                    if (res.data.userInfo) {
                                        authStore.setUserInfo(res.data.userInfo);
                                        userInfo.value = res.data.userInfo;
                                        userAvatar.value = res.data.userInfo.avatarUrl || '/static/default-avatar.png';
                                        userName.value = res.data.userInfo.nickName || '微信用户';
                                    } else {
                                        // 创建基本用户信息
                                        const basicUserInfo = {
                                            avatarUrl: '/static/default-avatar.png',
                                            nickName: '微信用户',
                                            openId: res.data.open_id
                                        };
                                        authStore.setUserInfo(basicUserInfo);
                                        userInfo.value = basicUserInfo;
                                        userAvatar.value = basicUserInfo.avatarUrl;
                                        userName.value = basicUserInfo.nickName;
                                    }

                                    uni.showToast({
                                        title: '登录成功',
                                        icon: 'success'
                                    });
                                } else {
                                    uni.showToast({
                                        title: '登录失败，请重试',
                                        icon: 'none'
                                    });
                                }
                            },
                            fail: (err) => {
                                console.error('登录请求失败', err);
                                uni.showToast({
                                    title: '网络错误，请重试',
                                    icon: 'none'
                                });
                            },
                            complete: () => {
                                uni.hideLoading();
                            }
                        });
                    } else {
                        uni.hideLoading();
                        uni.showToast({
                            title: '获取授权失败',
                            icon: 'none'
                        });
                    }
                },
                fail: () => {
                    uni.hideLoading();
                    uni.showToast({
                        title: '登录失败',
                        icon: 'none'
                    });
                }
            });
        }

        // 退出登录
        function logout() {
            uni.showModal({
                title: '提示',
                content: '确定要退出登录吗？',
                success: (res) => {
                    if (res.confirm) {
                        // 使用 authStore 登出
                        authStore.logout();
                        userInfo.value = null;
                        userAvatar.value = '';
                        userName.value = '';
                    }
                }
            });
        }

        // 从本地存储加载聊天历史记录
        function loadLocalChatHistory() {
            isHistoryLoading.value = true;

            try {
                const localHistory = uni.getStorageSync(localHistoryKey);
                if (localHistory) {
                    chatHistory.value = JSON.parse(localHistory);
                }
            } catch (e) {
                console.error('加载本地聊天记录失败', e);
            }

            isHistoryLoading.value = false;

            // 聊天记录加载后滚动到底部
            nextTick(() => {
                scrollToBottom();
            });
        }

        // 保存聊天记录到本地
        function saveLocalChatHistory() {
            try {
                // 如果超出最大限制，保留最近的消息
                let historyToSave = chatHistory.value;
                if (historyToSave.length > maxLocalHistoryItems) {
                    historyToSave = historyToSave.slice(
                        historyToSave.length - maxLocalHistoryItems
                    );
                }

                uni.setStorageSync(localHistoryKey, JSON.stringify(historyToSave));
            } catch (e) {
                console.error('保存聊天记录失败', e);
            }
        }

        // 清空聊天记录
        function clearChatHistory() {
            uni.showModal({
                title: '提示',
                content: '确定要清空所有聊天记录吗？',
                success: (res) => {
                    if (res.confirm) {
                        chatHistory.value = [];
                        uni.removeStorageSync(localHistoryKey);
                        uni.showToast({
                            title: '聊天记录已清空',
                            icon: 'success'
                        });
                    }
                }
            });
        }

        function startChat(userMessage, assistantMessageIndex) {
            // 使用 authStore 获取 token
            const token = authStore.token;
            // 如果获取参考资料失败，仍然继续使用原始问题调用DeepSeek API
            const requestTask = uni.request({
                url: 'https://tushuoit.com/api/ju/deepseek/chat',
                method: 'POST',
                enableChunked: true,
                responseType: "text",
                header: {
                    'accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Authorization': `${authStore.authHeader}`  // 使用 authStore 的 authHeader
                },
                data: {
                    prompt: userMessage,
                    apiKey: "juxianwenlv",
                    stream: true
                },
                success: (res) => {
                    // 处理流式响应完成的情况
                    if (chatHistory.value[assistantMessageIndex].content.trim() === '') {
                        // 如果流式响应失败或内容为空，显示错误信息
                        chatHistory.value[assistantMessageIndex].content = '抱歉，无法获取回复内容。';
                    }
                    saveLocalChatHistory();
                },
                fail: (err) => {
                    console.error('请求失败', err);
                    chatHistory.value[assistantMessageIndex].content = '网络错误，请检查您的网络连接。';
                    saveLocalChatHistory();
                },
                complete: () => {
                    isLoading.value = false;
                    nextTick(() => {
                        scrollToBottom();
                    });
                }
            });

            // 监听数据块接收事件
            requestTask.onChunkReceived((res) => {
                if (res && res.data) {
                    try {
                        // 将二进制数据转换为文本
                        const uint8Array = new Uint8Array(res.data);
                        let text = String.fromCharCode.apply(null, uint8Array);
                        text = decodeURIComponent(escape(text));

                        // 处理SSE数据块
                        const lines = text.split('\n');
                        for (const line of lines) {
                            if (line.startsWith('data: ')) {
                                // 过滤结束标记
                                if (line === 'data: [DONE]') {
                                    isLoading.value = false;
                                    continue;
                                }
                                const jsonData = line.substring(6); // 移除 "data: " 前缀
                                try {
                                    const data = JSON.parse(jsonData);
                                    // 处理OpenAI/DeepSeek格式的流式响应
                                    if (data.choices && data.choices[0]) {
                                        if (data.choices[0].delta && data.choices[0].delta.content) {
                                            // 将新的内容部分添加到当前消息中
                                            const chunk = data.choices[0].delta.content;
                                            chatHistory.value[assistantMessageIndex].content += chunk;
                                        }
                                        // 可能有些API返回格式略有不同
                                        else if (data.choices[0].message && data.choices[0].message.content) {
                                            const chunk = data.choices[0].message.content;
                                            chatHistory.value[assistantMessageIndex].content += chunk;
                                        }

                                        // 定期滚动到底部，但不要每个块都滚动，以避免卡顿
                                        if (Math.random() < 0.1) { // 约10%的概率滚动
                                            nextTick(() => {
                                                scrollToBottom();
                                            });
                                        }
                                    }
                                    // 处理其他可能的格式
                                    else if (data.data && data.data.text) {
                                        chatHistory.value[assistantMessageIndex].content += data.data.text;

                                        if (Math.random() < 0.1) {
                                            nextTick(() => {
                                                scrollToBottom();
                                            });
                                        }
                                    }
                                } catch (e) {
                                    console.error('解析JSON块失败', e, jsonData);
                                }
                            }
                        }
                    } catch (e) {
                        console.error('处理数据块失败', e);
                    }
                }
            });
        }

        // 提交问题
        function submit(userInputText) {
            // 使用传入的参数或当前输入值
            const userMessage = userInputText || input.value.trim();
            
            if (!userMessage) return;

            if (!authStore.isLoggedIn) {
                if (!hasPromptedLogin.value) {
                    login();
                } else {
                    uni.showToast({
                        title: '请先登录后再提问',
                        icon: 'none'
                    });
                }
                return;
            }

            chatHistory.value.push({
                type: 'user',
                content: userMessage
            });
            saveLocalChatHistory();

            input.value = '';
            isLoading.value = true;

            nextTick(() => {
                scrollToBottom();
            });

            // 使用 authStore 获取 token
            const token = authStore.token;

            // 先添加一个空的助手消息，用于流式更新
            let assistantMessageIndex = chatHistory.value.length;
            chatHistory.value.push({
                type: 'assistant',
                content: '',
                rawMarkdown: true
            });
            const useRAG = true;
            if (!useRAG || userMessage.length < 3) {
                const chatPrompt =
                    `如果用户问题涉及线路推荐，景点介绍，美食推荐，使用小红书风格回答。推荐的条数控制在7条以内。\n\n用户问题: ${userMessage}`;
                startChat(chatPrompt, assistantMessageIndex); // 继续使用原始问题调用DeepSeek API
            }
            // 第一步：通过RAG查询API获取参考资料
            // 注意：查询参数需要拼接在URL中，而不是放在请求体内
            if (useRAG && userMessage.length >= 3) {
                const encodedQuestion = encodeURIComponent(userMessage);
                const ragQueryUrl = `https://tushuoit.com/api/ju/text_rag/search?question=${encodedQuestion}&collection_name=rag_default&top_k=2&use_hyde=false`;

                uni.request({
                    url: ragQueryUrl,
                    method: 'POST',
                    header: {
                        'accept': 'application/json',
                        'Authorization': `${authStore.authHeader}`  // 使用 authStore 的 authHeader
                    },
                    // 不需要发送请求体数据，所有参数都在URL中
                    success: (res) => {
                        const ragRes = res.data;
                        // 第二步：使用参考资料和用户问题调用DeepSeek聊天API
                        let referenceContext = '';

                        try {
                            if (ragRes.data && ragRes.code == 0 && ragRes.data.length > 0) {
                                // 提取参考资料，并格式化为有用的上下文
                                const references = ragRes.data.map(item => {
                                    return item.content;
                                });
                                referenceContext = "参考资料：\n";

                                references.forEach((ref, index) => {
                                    if (ref && ref.length > 0) {
                                        referenceContext += `${index + 1}. ${ref}\n`;
                                    }
                                });
                            }
                        } catch (err) {
                            console.error('处理参考资料失败', err);
                            // 如果参考资料处理失败，继续使用空的参考上下文
                        }

                        console.log('参考资料上下文:', referenceContext);

                        // 构建包含参考资料的提示词
                        const augmentedPrompt = referenceContext ?
                            `请结合以下参考资料回答用户问题。如果参考资料不相关，请忽略并直接回答。如果用户问题涉及线路推荐，景点介绍，美食推荐，使用小红书风格回答。推荐的条数控制在7条以内。\n\n${referenceContext}\n\n用户问题: ${userMessage}` :
                            userMessage;

                        startChat(augmentedPrompt, assistantMessageIndex); // 使用增强的提示词调用DeepSeek API
                    },
                    fail: (err) => {
                        console.error('获取参考资料失败', err);
                        startChat(chatPrompt, assistantMessageIndex); // 继续使用原始问题调用DeepSeek API

                    }
                });
            }

        }

        // 滚动到底部
        function scrollToBottom() {
            // 使用 nextTick 确保在DOM更新后执行
            nextTick(() => {
                // 使用 setTimeout 进一步确保渲染完成后执行
                setTimeout(() => {
                    const query = uni.createSelectorQuery();
                    query.selectAll('.message-item').boundingClientRect();
                    query.select('.chat-container').boundingClientRect();
                    query.exec((res) => {
                        if (res && res[0] && res[1]) {
                            // 计算所有消息项的总高度
                            const messageItems = res[0];
                            const container = res[1];

                            let totalHeight = 0;

                            // 遍历所有消息项，计算总高度
                            messageItems.forEach(item => {
                                totalHeight += item.height;
                            });

                            // 添加额外的高度以确保滚动到底部
                            totalHeight += 160; // 额外空间确保完全滚动到底部

                            // 更新滚动位置
                            scrollTop.value = totalHeight;
                            console.log('Scrolling to:', totalHeight);
                        }
                    });
                }, 100); // 小延迟以确保渲染完成
            });
        }

        // 初始化录音管理器
        function initRecorderManager() {
            recorderManager = uni.getRecorderManager();

            recorderManager.onStop((res) => {
                if (isRecording.value) {
                    isRecording.value = false;

                    if (res.duration < 1000) {
                        uni.showToast({
                            title: '说话时间太短',
                            icon: 'none'
                        });
                        return;
                    }

                    uni.showLoading({
                        title: '语音识别中...'
                    });

                    // 上传录音文件进行语音识别
                    const token = authStore.token;

                    uni.uploadFile({
                        url: 'https://tushuoit.com/api/ju/speech-to-text',
                        filePath: res.tempFilePath,
                        name: 'audio',
                        header: {
                            Authorization: `${authStore.authHeader}`  // 使用 authStore 的 authHeader
                        },
                        success: (uploadRes) => {
                            const data = JSON.parse(uploadRes.data);
                            if (data.text) {
                                input.value = data.text;
                            } else {
                                uni.showToast({
                                    title: '语音识别失败',
                                    icon: 'none'
                                });
                            }
                        },
                        fail: () => {
                            uni.showToast({
                                title: '语音上传失败',
                                icon: 'none'
                            });
                        },
                        complete: () => {
                            uni.hideLoading();
                        }
                    });
                }
            });
        }

        // 开始录音
        function startVoiceRecord() {
            // 保留此函数以保持与之前代码的兼容性
            // 实际的语音功能由VoiceTextInput组件处理
        }

        // 结束录音
        function stopVoiceRecord() {
            // 保留此函数以保持与之前代码的兼容性
            // 实际的语音功能由VoiceTextInput组件处理
        }

        // 使用建议问题功能
        function useQuestion(question) {
            input.value = question;
            submit();
        }

        // 初始化marked配置
        function initMarked() {
            marked.setOptions({
                renderer: new marked.Renderer(),
                highlight: function (code, lang) {
                    if (Prism.languages[lang]) {
                        return Prism.highlight(code, Prism.languages[lang], lang);
                    } else {
                        return code;
                    }
                },
                pedantic: false,
                gfm: true,
                breaks: true,
                sanitize: false,
                smartLists: true,
                smartypants: false,
                xhtml: false
            });
        }

        // 渲染Markdown内容
        function renderMarkdown(content) {
            try {
                if (!content) return '';

                // 使用marked将markdown转为HTML
                let html = marked.parse(content);

                // 移除DOMPurify相关代码，小程序环境不支持
                // 如果需要HTML净化，可以考虑使用正则表达式或其他小程序兼容的方法

                // 返回富文本所需的内容格式
                return html;
            } catch (error) {
                console.error('Markdown渲染失败:', error);
                return content; // 出错时返回原始文本
            }
        }

        // 返回所有需要在模板中使用的属性和方法
        return {
            userAvatar,
            userName,
            userInfo,
            input,
            chatHistory,
            isLoading,
            isRecording,
            isHistoryLoading,
            scrollTop,
            handleUserClick,
            login,
            logout,
            loadLocalChatHistory,
            saveLocalChatHistory,
            clearChatHistory,
            submit,
            scrollToBottom,
            startVoiceRecord,
            stopVoiceRecord,
            useQuestion,
            showLoginModal,
            hasPromptedLogin,
            cancelLogin,
            handleLogin,
            renderMarkdown, // 添加Markdown渲染方法
        }
    }
})
</script>

<style>
.container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f8f0e3;
    /* Changed from #f5f5f5 to match index.vue */
    padding-bottom: 50px;
}

.header {
    display: flex;
    justify-content: flex-end;
    padding: 10px 15px;
    background-color: #d9b38c;
    /* Changed from #ffffff to match index.vue */
    border-bottom: 1px solid #e5e5e5;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: 1px solid #e0e0e0;
}

.chat-container {
    flex: 1;
    padding: 10px 8px;
    overflow-y: auto;
}

.loading {
    text-align: center;
    padding: 10px 0;
    color: #999;
}

.message-item {
    display: flex;


    margin-bottom: 15px;
}

.message-item.user {
    flex-direction: row-reverse;
}

.message-avatar {
    width: 40px;
    height: 40px;
    margin: 0 10px;
}

.message-avatar image {
    width: 40px;
    height: 40px;
    border-radius: 50%;
}

.message-content {
    max-width: 70%;
    padding: 10px 15px;
    border-radius: 8px;
    word-break: break-all;
}

.user .message-content {
    background-color: #8b6b4a;
    /* Changed from #007aff to match index.vue */
    color: white;
    border-top-right-radius: 0;
}

.assistant .message-content {
    background-color: white;
    color: #333;
    border-top-left-radius: 0;
}

.input-area {
    padding: 10px 15px;
    background-color: #e8d0b5;
    border-top: 1px solid #d9b38c;
}

/* 覆盖旧的输入样式 */
.input-box, 
.send-button,
.input-wrapper,
.voice-btn,
.send-btn {
    display: none;
}

/* 底部安全区域 */
.safe-bottom {
    height: env(safe-area-inset-bottom);
}

/* 空状态提示样式 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 30px 15px;
}

.empty-image {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    margin-bottom: 15px;
}

.empty-text {
    font-size: 16px;
    color: #666;
    text-align: center;
    margin-bottom: 20px;

}

.suggestion-container {
    width: 100%;
}

.suggestion-item {
    background-color: #fff;
    padding: 10px 15px;
    border-radius: 20px;
    margin-bottom: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.suggestion-item text {
    color: #8b6b4a;
    /* Changed from #007aff to match index.vue */
}

/* 图标文本样式（替代uni-icons） */
.icon-text {
    font-size: 14px;
}

.loading-icon {
    animation: rotate 1s linear infinite;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

/* 登录模态框样式 */
.login-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;




}

.login-container {
    width: 80%;
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;

}

.login-title {
    text-align: center;
    font-size: 18px;
    font-weight: bold;

    margin-bottom: 15px;

}

.login-content {
    text-align: center;
    color: #666;
    margin-bottom: 20px;
}

.login-buttons {
    display: flex;
    justify-content: space-between;

}

.cancel-btn,
.login-btn {
    width: 45%;
    padding: 10px 0;
    border-radius: 5px;
    text-align: center;

}

.cancel-btn {
    background-color: #f2f2f2;
    color: #666;
}

.login-btn {
    background-color: #8b6b4a;
    /* Changed from #007aff to match index.vue */
    color: white;

}

/* 添加Markdown样式 */
.markdown-content {
    width: 100%;






}

/* Markdown样式 */
.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
    margin-top: 16px;
    margin-bottom: 8px;
    font-weight: 600;
    line-height: 1.25;
}

.markdown-content h1 {
    font-size: 20px;
}

.markdown-content h2 {
    font-size: 18px;
}

.markdown-content h3 {
    font-size: 16px;
}

.markdown-content p {
    margin-bottom: 10px;

}

.markdown-content ul,
.markdown-content ol {
    margin-bottom: 10px;
    padding-left: 20px;


}

.markdown-content ul {
    list-style-type: disc;

}

.markdown-content ol {
    list-style-type: decimal;



}

.markdown-content li {







    margin-bottom: 5px;
}

.markdown-content code {
    background-color: #f1f1f1;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
}

.markdown-content pre {
    background-color: #f6f8fa;
    padding: 10px;
    border-radius: 5px;
    overflow-x: auto;
    margin-bottom: 10px;
}

.markdown-content blockquote {
    border-left: 3px solid #dfe2e5;
    padding-left: 10px;
    color: #6a737d;
    margin: 0 0 10px;
}

.markdown-content a {
    color: #8b6b4a;
    /* Changed from #007aff to match index.vue */
    text-decoration: underline;
}

.markdown-content img {
    max-width: 100%;
    margin: 10px 0;
}

.markdown-content table {
    border-collapse: collapse;
    width: 100%;
    margin-bottom: 10px;
}

.markdown-content table th,
.markdown-content table td {
    border: 1px solid #ddd;
    padding: 8px;
}

.markdown-content table th {
    background-color: #f6f8fa;
    font-weight: bold;
}

/* 适配用户消息和助手消息中的Markdown样式 */
.user .markdown-content {
    color: white;
}

.assistant .markdown-content {
    color: #333;
}

.assistant .markdown-content pre,
.assistant .markdown-content code {
    background-color: #eee;
    color: #333;
}

/* 添加清除历史记录按钮样式 */
.clear-history-button {
    display: flex;
    justify-content: center;
    margin: 10px 0;
}

.clear-history-text {
    background-color: rgba(139, 107, 74, 0.1);
    color: #8b6b4a;
    font-size: 14px;
    padding: 6px 12px;
    border-radius: 15px;
    border: 1px solid rgba(139, 107, 74, 0.2);
}
</style>
